<template>
  <div>
    <el-form v-loading="formLoading" ref="pram" :model="pram" label-width="100px" @submit.native.prevent>
      <el-form-item label="角色名称" prop="role_name" :rules="[{required:true,message:'请填写角色名称', trigger:['blur','change']}]">
        <el-input v-model="pram.role_name" maxlength="20" placeholder="身份名称" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="perms"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as roleApi from '@/api/role.js'
import {Debounce} from '@/utils/validate'
export default {
  name: "roleEdit",
  props: {
    //限制类型，并作为一个对象去使用
    isCreate: {
      //0新增 1更新
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: null
    },
  },
  data() {
    return {
      pram: {
        role_name: '',
        rules: '',
        status: 0,
        id: 0
      },
      formLoading:false,
      menuList:[],
      menuExpand: false,
      menuOptions:[],
      menuCheckStrictly: true,
      currentNodeId:[],
      defaultProps: {
        children: "childList",
        label: "name",
      },
      menuIds:[],
    }
  },
  mounted() {
    this.initEditData();
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },

    initEditData() {
      const {  role_name, status, id } = this.editData
      this.pram.role_name = role_name
      this.pram.status = status
      this.pram.id = id
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
      });
      roleApi.getRoleTreeById({id}).then(res=>{
      //后期接口调用
        this.menuOptions = res;
        loading.close();
        this.getTreeId(res)
        this.$nextTick(()=>{
          this.menuIds.forEach((i,n) =>{
            var node = this.$refs.menu.getNode(i);
            if(node.isLeaf){
              this.$refs.menu.setChecked(node, true);
            }
          })
        })
      })
    },
    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        this.formLoading=true;
        let roles = this.getMenuAllCheckedKeys().toString();
        this.pram.rules = roles;
        roleApi.saveRole(this.pram).then(data => {
          this.$message.success('保存成功')
          this.$emit('hideEditDialog')
        }).finally(()=>{
          this.formLoading=false
        })
      })
    }),
    rulesSelect(selectKeys) {
      this.pram.rules = selectKeys
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].perms].expanded = value;
        }
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getTreeId(datas) {
      for(var i in datas){
        if(datas[i].checked) this.menuIds.push(datas[i].perms)
        if(datas[i].childList){
          this.getTreeId(datas[i].childList);
        }
      }
    },
  }
}
</script>

<style scoped>

</style>
